package com.iqik.rocket.config;

import com.iqik.rocket.dao.OrderRepository;
import com.iqik.rocket.pojo.Order;
import com.iqik.rocket.pojo.OrderStatus;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Optional;

@Slf4j
@Component
@RocketMQMessageListener(topic = "tp_pay_02", consumerGroup = "consume_pay")
public class PayRocketListener implements RocketMQListener<String> {

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private RedisTemplate<String, Integer> redisTemplate;

    @Override
    public void onMessage(String s) {
        Optional<Order> result = orderRepository.findById(s);
        Order order = result.get();
        switch (order.getStatus()){
            case NEW:
            case CANCEL:
                log.info("订单： " + s + " 超时未支付 已经取消");
                order.setStatus(OrderStatus.CANCEL);
                redisTemplate.opsForValue().increment("good_count", 1l);
                orderRepository.updateOrder(order.getId(), order.getStatus());
                break;
            case PAYED:
                log.info("订单: " + s + " 完成支付。");
                break;
        }
    }
}
